<script lang="ts" setup>
import { isDark } from '@/utils/is'
import { useAppStore } from '@/store/modules/app'
import { useDesign } from '@/hooks/web/useDesign'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import routerSearch from '@/components/RouterSearch/index.vue'
import { loanApi } from './api/system/loan'
import { customerApi } from './api/system/customer'
import { ElNotification } from 'element-plus'

defineOptions({ name: 'APP' })

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('app')
const appStore = useAppStore()
const currentSize = computed(() => appStore.getCurrentSize)
const greyMode = computed(() => appStore.getGreyMode)
const { wsCache } = useCache()
const router = useRouter();

// 根据浏览器当前主题设置系统主题色
const setDefaultTheme = () => {
  let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
  if (isDarkTheme === null) {
    isDarkTheme = isDark()
  }
  appStore.setIsDark(isDarkTheme)
}
setDefaultTheme()

const loanList = ref([]);
provide('loanList', loanList);
function getLoanList() {
  loanApi
  .getLoanList()
  .then(data => {
    loanList.value = data.map(content => ({
      id: Math.random().toString(36).slice(2),
      content,
    }));
  });
}
provide('getLoanList', getLoanList);

/** 检查新客户的函数 */
async function checkNewCustomers() {
  try {
    // 调用新客户接口（无需参数）
    const res = await customerApi.getNewCustomer();

    // 处理响应数据 - 根据实际API响应结构调整
    if ( !(res && 0 < res.length) ) { return; }

    ElNotification({
      title: '新客户提醒',
      message: `您有 ${res.length} 位新客户，请前往处理`,
      type: 'success',
      position: 'bottom-right',
      onClick: () => {
        // 关闭所有通知
        ElNotification.closeAll()
        // 点击通知时跳转到我的客户页面
        router.push('/customer/index');
      }
    })
  } catch (error) {
    console.error('检查新客户失败:', error)
  }
}

// 组件挂载时开始定时检查
onMounted(() => {
  // 立即执行一次检查
  checkNewCustomers()

  const interval = setInterval(checkNewCustomers, 30000)

  // 使用 onBeforeUnmount 替代 onUnmounted
  onBeforeUnmount(() => {
    clearInterval(interval)
  })
})
</script>
<template>
  <ConfigGlobal :size="currentSize">
    <RouterView :class="greyMode ? `${prefixCls}-grey-mode` : ''" />
    <routerSearch />
  </ConfigGlobal>
</template>
<style lang="scss">
$prefix-cls: #{$namespace}-app;

.size {
  width: 100%;
  height: 100%;
}

html,
body {
  @extend .size;

  padding: 0 !important;
  margin: 0;
  overflow: hidden;

  #app {
    @extend .size;
  }
}

.#{$prefix-cls}-grey-mode {
  filter: grayscale(100%);
}
</style>
